package cn.chinaflame.pagodas.service;

import cn.chinaflame.pagodas.Result.Result;
import cn.chinaflame.pagodas.enums.CodeEnum;
import cn.chinaflame.pagodas.utils.HttpPostUtil;
import cn.chinaflame.pagodas.utils.LightAlgo.LightOp;
import cn.chinaflame.pagodas.vo.LightVO;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

@Service
public class WrmNIService {

    private final static Logger log = LoggerFactory.getLogger(WrmNIService.class);

    @Value("${iisserviceurl}")
    private String endpoint;

    /**
     * 调用WebService启动服务器小助手
     */
    public void launchServer() {
        final String launchServer = endpoint + "/launchServer";
        log.info("launchServer:{}",launchServer);
        HttpPostUtil.sendGet(launchServer, "");
    }

    /**
     * 调用WebService开启硬件服务器连接
     */
    public void lighton() {
        final String lighton = endpoint + "/lighton";
        log.info("lighton:{}",lighton);
        HttpPostUtil.sendGet(lighton, "");
    }

    /**
     * 调用WebService关闭硬件服务器连接
     */
    public void lightoff() {
        final String lightoff = endpoint + "/lightoff";
        log.info("lightoff:{}",lightoff);
        HttpPostUtil.sendGet(lightoff, "");
    }

    /**
     * 调用WebService寻灯接口
     * @param request
     * @param lightno
     * @return
     */
    public List<LightVO> lightSearch(String lightnos) {
        final String lightSearch = endpoint + "/LightSearch";
        log.info("lightSearch:{}",lightSearch);
        List<LightVO> list = paramCheck(lightnos);
        if (list != null && list.size() == 1) {
            LightVO vo = list.get(0);
            if (StringUtils.isBlank(vo.getLightno()) && vo.getResult() == 0) {
                return list;
            }
        }
        //HttpPostUtil.sendGet(uri, "lightnos="+lightnos);// LightniWebService.invokeLightClear(lightnos);
        String result = HttpPostUtil.doPost1(lightSearch, "lightnos=" + lightnos);
        String body = HttpPostUtil.getBody(result);
        JSONObject obj = JSONObject.parseObject(body);
        Iterator<Entry<String, Object>> it = obj.entrySet().iterator();
        list = Lists.newArrayList();
        list.clear();
        while (it.hasNext()) {
            Entry<String, Object> entry = it.next();
            JSONObject innerobj = obj.getJSONObject(entry.getKey());
            list.add(new LightVO(LightOp.lightSearch.toString(),entry.getKey(),entry.getKey(), innerobj.getIntValue("result"), 0,LightOp.lightSearch.toString(),innerobj.toJSONString()));
        }
        log.info("lightSearch:list:{}",JSONArray.toJSONString(list));
        return list;
    }

    /**
     * 调用WebService批量寻灯和安灯接口
     *
     * @param request
     * @param lightvo
     * @return
     */
    public List<LightVO> lightCheckAndSend(String lightvo) {
//    	JSONArray json = JSONArray.parseArray(lightvo);
//    	JSONObject ooo = (JSONObject) json.get(0);
//    	ooo.put("lightno", "0601010605");
//    	json.clear();
//    	json.add(ooo);
//    	lightvo = json.toJSONString();
//    	System.out.println("@@@@@@@"+json);
        final String lightSearchAndSend = endpoint + "/LightCheckAndSend";
        log.info("lightSearchAndSend:{}",lightSearchAndSend);
        List<LightVO> list = paramCheck(lightvo);
        if (list != null && list.size() == 1) {
            LightVO vo = list.get(0);
            if (StringUtils.isBlank(vo.getLightno()) && vo.getResult() == 0) {
                return list;
            }
        }
        //HttpPostUtil.sendGet(uri, "lightnos="+lightnos);// LightniWebService.invokeLightClear(lightnos);
        String result = HttpPostUtil.doPost1(lightSearchAndSend, "json=" + lightvo);
        String body = HttpPostUtil.getBody(result);
        JSONObject obj = JSONObject.parseObject(body);
        Iterator<Entry<String, Object>> it = obj.entrySet().iterator();
        list = Lists.newArrayList();
        list.clear();
        JSONArray array = JSONArray.parseArray(lightvo);
        while (it.hasNext()) {
            Entry<String, Object> entry = it.next();
            List<Object> beans = (List<Object>) array.stream().filter(light ->JSONObject.toJSONString(light).contains(entry.getKey())).collect(Collectors.toList());
        	String params = JSONObject.toJSONString(beans.get(0));
            JSONObject innerobj = obj.getJSONObject(entry.getKey());
            LightVO vo = new LightVO(LightOp.lightCheckAndSend.toString(),params,entry.getKey(), innerobj.getIntValue("result"), 0,LightOp.lightCheckAndSend.toString(),innerobj.toJSONString());
            list.add(vo);
//			log.info(JSONObject.toJSONString(vo));
        }
        log.info("lightCheckAndSend:list:{}",JSONArray.toJSONString(list));
        return list;
    }

    /**
     * 调用WebService批量安灯接口
     *
     * @param request
     * @param lightno
     * @param obj
     * @return
     */
    public List<LightVO> lightSend(String lightvo) {//String lightno, String obj
        final String lightSend = endpoint + "/LightSend";
        log.info("lightSend:{}",lightSend);
        List<LightVO> list = paramCheck(lightvo);
        if (list != null && list.size() == 1) {
            LightVO vo = list.get(0);
            if (StringUtils.isBlank(vo.getLightno()) && vo.getResult() == 0) {
                return list;
            }
        }
        //HttpPostUtil.sendGet(uri, "lightnos="+lightnos);// LightniWebService.invokeLightClear(lightnos);
        String result = HttpPostUtil.doPost1(lightSend, "json=" + lightvo);
        String body = HttpPostUtil.getBody(result);
        JSONObject obj = JSONObject.parseObject(body);
        Iterator<Entry<String, Object>> it = obj.entrySet().iterator();
        list = Lists.newArrayList();
        list.clear();
        JSONArray array = JSONArray.parseArray(lightvo);
        while (it.hasNext()) {
        	Entry<String, Object> entry = it.next();
        	List<Object> beans = (List<Object>) array.stream().filter(light ->JSONObject.toJSONString(light).contains(entry.getKey())).collect(Collectors.toList());
        	String params = JSONObject.toJSONString(beans.get(0));
            JSONObject innerobj = obj.getJSONObject(entry.getKey());
            LightVO vo = new LightVO(LightOp.lightSend.toString(),params,entry.getKey(), innerobj.getIntValue("result"), 0,LightOp.lightSend.toString(),innerobj.toJSONString());
//		 log.info(JSONObject.toJSONString(vo));
            list.add(vo);
        }
        log.info("lightSend:list:{}",JSONArray.toJSONString(list));
        return list;
    }

    /**
     * 调用WebService批量清灯接口
     *
     * @param request
     * @param lightno
     * @return
     */
    public List<LightVO> lightClear(String lightnos) {
        final String lightClear = endpoint + "/LightClear";
        log.info("lightClear:{}",lightClear);
        List<LightVO> list = paramCheck(lightnos);
        if (list != null && list.size() == 1) {
            LightVO vo = list.get(0);
            if (StringUtils.isBlank(vo.getLightno()) && vo.getResult() == 0) {
                return list;
            }
        }
        //HttpPostUtil.sendGet(uri, "lightnos="+lightnos);// LightniWebService.invokeLightClear(lightnos);
        String result = HttpPostUtil.doPost1(lightClear, "lightnos=" + lightnos);
        String body = HttpPostUtil.getBody(result);
        JSONObject obj = JSONObject.parseObject(body);
        Iterator<Entry<String, Object>> it = obj.entrySet().iterator();
        list = Lists.newArrayList();
        list.clear();
        while (it.hasNext()) {
            Entry<String, Object> entry = it.next();
            JSONObject innerobj = obj.getJSONObject(entry.getKey());
            LightVO vo = new LightVO(LightOp.lightClear.toString(),entry.getKey(),entry.getKey(), innerobj.getIntValue("result"), 0,LightOp.lightClear.toString(),innerobj.toJSONString());
            list.add(vo);
            log.info(JSONObject.toJSONString(vo));
        }
        log.info("lightClear:list:{}",JSONArray.toJSONString(list));
        return list;
    }

    /**
     * 调用WebService批量检查灯位接口
     *
     * @param lightno
     * @return
     */
    public List<LightVO> lightCheck(String lightnos) {    
    	final String lightCheck = endpoint + "/LightCheck";
    	log.info("lightCheck:{}",lightCheck);
	    List<LightVO> list = paramCheck(lightnos);
	    if (list != null && list.size() == 1) {
	        LightVO vo = list.get(0);
	        if (StringUtils.isBlank(vo.getLightno()) && vo.getResult() == 0) {
	            return list;
	        }
	    }
	    //HttpPostUtil.sendGet(uri, "lightnos="+lightnos);// LightniWebService.invokeLightClear(lightnos);
	    String result = HttpPostUtil.doPost1(lightCheck, "lightnos=" + lightnos);
	    String body = HttpPostUtil.getBody(result);
	    JSONObject obj = JSONObject.parseObject(body);
	    Iterator<Entry<String, Object>> it = obj.entrySet().iterator();
	    list = Lists.newArrayList();
	    list.clear();
	    while (it.hasNext()) {
	        Entry<String, Object> entry = it.next();
	        JSONObject innerobj = obj.getJSONObject(entry.getKey());
	        LightVO vo = new LightVO(LightOp.lightCheck.toString(),entry.getKey(),entry.getKey(), innerobj.getIntValue("result"), 0,LightOp.lightCheck.toString(),innerobj.toJSONString());
	        list.add(vo);
	    }
	    log.info("lightCheck:list:{}",JSONArray.toJSONString(list));
	    return list;
    }

    /**
     * 发送配置
     *
     * @param request
     * @param seateinfo
     * @return
     */
    public Result LightConfigure(String lightnos) {
		/*Result checkresult = paramCheck(lightnos) ;
		if(checkresult != null && StringUtils.isNotEmpty(checkresult.getCode()) && checkresult.getCode().toLowerCase().equals(CodeEnum.FAIL.getCode().toLowerCase())) {
			return checkresult;
		}
	  String result = LightniWebService.invokeLightConfigure(lightnos);
	  ResponseFormat  responseformat = JSONObject.parseObject(result, ResponseFormat.class);
		 switch(responseformat.getResult()) {
		 case 0:
			 return Result.create(CodeEnum.FAIL.getCode(), responseformat.getMessage());
		 case 1:
			return Result.create(CodeEnum.SUCCESS.getCode(), responseformat.getMessage());
			 default :break;
		 }*/
        return null;
    }

    /**
     * 灯号参数验证
     * @param lightnos
     * @return
     */
    private List<LightVO> paramCheck(String lightnos) {
        List<LightVO> list = Lists.newArrayList();
        //try {
			/*if(!IPUtil.IsValidIp(ipaddr)) {
				return Result.create("ERROR", "请输入正确的IP地址");
			};*/
		/*} catch (IOException e) {
			e.printStackTrace();
			return Result.create("ERROR","连接指令服务失败，请检查网络及IP是否正常");
		}*/
        if (StringUtils.isBlank(lightnos)) {
            list.add(new LightVO("", 0, "请输入手机号或寻灯编号,若有多个，请用逗号隔开"));
        }
        return list;
    }

    /**
     * 点灯接口
     * @param lightno   灯号
     * @param obj       祝福人
     * @param bless     祝福语
     * @return
     */
    public LightVO wwtLightSend (String lightno,String obj,String bless) {
        Map<String,Object> map = Maps.newHashMap();
        map.put("lightno",lightno);
        map.put("obj",obj);
        map.put("bless",bless);
        List<Map<String,Object>> list = Lists.newArrayList();
        list.add(map);
        Gson gson = new Gson();
        //HttpPostUtil.sendGet(endpoint + "/launchServer", "");
        HttpPostUtil.sendGet(endpoint + "/lighton", "");
        String var = HttpPostUtil.doPost1(endpoint+"/LightSend","json="+gson.toJson(list));
        return getLightVO(var,LightOp.lightSend.toString());
    }

    /**
     * 寻灯接口
     * @param lightno   灯号
     * @return
     */
    public LightVO wwtLightCheck (String lightno) {
        //HttpPostUtil.sendGet(endpoint + "/launchServer", "");
        HttpPostUtil.sendGet(endpoint + "/lighton", "");
        String var = HttpPostUtil.doPost1("http://112.5.74.208:8050/WebService.asmx/LightCheck","lightnos="+lightno);
        return getLightVO(var,LightOp.lightSend.toString());
    }

    /**
     * 闪灯接口
     * @param lightno   灯号
     * @return
     */
    public LightVO wwtLightSearch (String lightno) {
        //HttpPostUtil.sendGet(endpoint + "/launchServer", "");
        HttpPostUtil.sendGet(endpoint + "/lighton", "");
        String var = HttpPostUtil.doPost1("http://112.5.74.208:8050/WebService.asmx/LightSearch","lightnos="+lightno);
        return getLightVO(var,LightOp.lightSend.toString());
    }

    /**
     * 清灯接口
     * @param lightno
     * @return
     */
    public LightVO wwtLightClear (String lightno) {
        //HttpPostUtil.sendGet(endpoint + "/launchServer", "");
        HttpPostUtil.sendGet(endpoint + "/lighton", "");
        String var = HttpPostUtil.doPost1("http://112.5.74.208:8050/WebService.asmx/LightClear","lightnos="+lightno);
        return getLightVO(var,LightOp.lightSend.toString());
    }

    /**
     * 解析XML转化LightVo对线
     * @param str
     * @return
     */
    public LightVO getLightVO (String str,String type) {

        LightVO lightVO = null;
        String body = HttpPostUtil.getBody(str);
        JSONObject obj = JSONObject.parseObject(body);
        Iterator<Map.Entry<String, Object>> it = obj.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            JSONObject innerobj = obj.getJSONObject(entry.getKey());
            lightVO = new LightVO(type,entry.getKey(),entry.getKey(), innerobj.getIntValue("result"), 0,type,innerobj.toJSONString());
        }
        return lightVO;
    }
}
